<?php

namespace App\Utils;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

trait ControllerModelTrait
{
    /**
     * 分页获取数据
     * @param $model
     * @param $request
     * @param string $sort
     * @return false|LengthAwarePaginator
     */
    public function getPagedData($model, $request, string $sort = 'id'): LengthAwarePaginator|bool
    {
        if ($model instanceof Builder) {
            $pageSize = $request->input('pageSize', 10);
            if (str_contains($sort, 'asc')) {
                $sortKey = trim(str_replace('asc', '', $sort));
                $paginate = $model->orderBy($sortKey)->paginate($pageSize);
            } else
                $paginate = $model->orderByDesc($sort)->paginate($pageSize);
            return $paginate;
        } else
            return false;
    }

    /**
     * 获取数据
     * @param $model
     * @return false|Builder[]|Collection
     */
    public function getAllData($model): Collection|bool|array
    {
        if ($model instanceof Builder)
            return $model->orderByDesc('id')->get();
        else
            return false;
    }

    /**
     * 保存数据
     * @param $model
     * @param $data
     * @return void
     */
    public function saveData($model, $data): void
    {
        if ($model instanceof Model) {
            if (isset($data['id']) && $data['id'])
                $model->where('id', $data['id'])->update($data);
            else
                $model->create($data);
        }
    }

    /**
     * 删除数据
     * @param $model
     * @param $ids
     * @return void
     */
    public function deleteData($model, $ids): void
    {
        if ($model instanceof Model) {
            if (str_contains($ids, ','))
                $model->whereIn('id', explode(',', $ids))->delete();
            else
                $model->where('id', $ids)->delete();
        }
    }

    /**
     * 分页格式返回
     * @param $pagination
     * @param $data
     * @return array
     */
    public function getPaginate($pagination, $data): array
    {
        return [
          'total'  => $pagination->total(),
          'page'   => $pagination->currentPage(),
          'page_size'  => $pagination->perPage(),
          'pages'  => $pagination->lastPage(),
          'list'   => $data
        ];
    }
}
